<?php

namespace Apps\AppApi\Method\Search;


use Apps\Common\Enum\SearchDataType;
use Apps\Common\Libs\PicUrl;
use PhalconPlus\Api\Common\ResultStatus;
use Apps\Common\Models\Question as QuestionModel;
use Phalcon\Mvc\Model;
use Apps\Common\Models\QuestionFollow;

/**
 * 搜索问答
 * @author      545
 * @date        2016年1月19日
 * @version     1.1.2
 * @copyright   Copyright 2015 meelier.com
 */
class Question extends BaseSearch
{
    public function run()
    {
        $keyword = $this->getDataItem('keyword');//关键字
        $type = intval($this->getDataItem('type',0));//分类 0 所有 1专家已回 2专家未回
        $order = $this->getDataItem('order','new');//排序
        $userid = $this->getDataItem('user_id',0);
        
        switch ($type){
            case 1:$where='is_expert_reply = 1';break;
            case 2:$where='is_expert_reply = 0';break;
            default:$where = '';break;
            
        }
        
        $orderBy = $order =="hot" ?"question_browsers DESC":"question_addtime DESC";
        $where = $where==''?'':"$where AND " ;
        //条数
        $count = $this->getConfig()->limit;
        if(empty($keyword)){//如果上传关键字为空 直接分页返回默认条件数据
        	$page = intval($this->getDataItem('page',1));
        	$offset = ($page-1)*$count;
        	$where .= " Apps\Common\Models\Question.question_state > 0 ";
        	$list=QuestionModel::query() 
        	->columns(['u.user_id',
                   	'u.user_nickname',
                    'u.user_cover',
        	        'u.user_gender',
        			'Apps\Common\Models\Question.question_id as question_id',
        			'Apps\Common\Models\Question.question_content as question_content',
        			'Apps\Common\Models\Question.question_pics as question_pics',
        			'Apps\Common\Models\Question.answer_num as answer_num',
        			'Apps\Common\Models\Question.question_follows as follow_num',
        			'Apps\Common\Models\Question.question_browsers',
        			'Apps\Common\Models\Question.question_addtime',
        	        'question_tag',
        			'Apps\Common\Models\Question.question_state as question_state',
        	        'Apps\Common\Models\Question.is_expert_reply as is_expert_reply'
        			])
        	->leftJoin('Apps\Common\Models\UserBase',
        	'Apps\Common\Models\Question.user_id=u.user_id','u')
        	->where($where)
        	->orderBy($orderBy)
        	->limit($count,$offset)
        	->execute()->toArray();
        	$QuestionFollow = new QuestionFollow();
        	foreach ($list as $k=>$v){
        	    // 是否收藏过
        	    if ($userid) {
        	        $list[$k]['is_collection'] = $QuestionFollow->is_follow($v['question_id'], $userid);
        	    } else {
        	        $list[$k]['is_collection'] = '0';
        	    }
        		$list[$k]['question_pics']=json_decode($list[$k]['question_pics'],true);
        		
        		if(unserialize(base64_decode($list[$k]['question_content']))){
        		    $list[$k]['question_content'] = unserialize(base64_decode($list[$k]['question_content']));
        		}
        		
        		$list[$k]['question_tag'] = $v['question_tag'] ? json_decode($v['question_tag'], true) : null;
        		
        		if(count($list[$k]['question_pics']) > 2){
        			$list[$k]['question_pics'] =  array_slice($list[$k]['question_pics'], 0, 2);
        		}
        		$list[$k]['user_cover']="http://img.meelier.com/".$list[$k]['user_cover'];
        		foreach ($list[$k]['question_pics'] as $key=>$val){
        			$list[$k]['question_pics'][$key]="http://img.meelier.com/".$list[$k]['question_pics'][$key];
        		}
        	}
        	$this->setResult($list);
        }else{//关键词不为空根据关键词查询
	        
        	$keywordarr=explode(" ",trim($keyword));
        	foreach ($keywordarr as $r){
        		$wherearr[]="Apps\Common\Models\Question.question_content like '%".$r."%'";
        		$r = $this->mysql_unicode_encode($r);
        		$wherearr[]="Apps\Common\Models\Question.question_tag like '%".$r."%'";
        	}
        	$wheretemp = implode(" or ",$wherearr);
        	$where .= " ($wheretemp ) ";
        	
        	//////////////////////////////////////////////////////////////////////
        	$page = intval($this->getDataItem('page',1));
        	$offset = ($page-1)*$count;
        	
        	$list=QuestionModel::query()
        	->columns(['u.user_id',
        			'u.user_nickname',
        			'u.user_cover',
        	        'u.user_gender',
        			'Apps\Common\Models\Question.question_id as question_id',
        			'Apps\Common\Models\Question.question_content as question_content',
        			'Apps\Common\Models\Question.question_pics as question_pics',
        			'Apps\Common\Models\Question.answer_num as answer_num',
        			'Apps\Common\Models\Question.question_follows as follow_num',
        			'Apps\Common\Models\Question.question_browsers',
        			'Apps\Common\Models\Question.question_addtime',
        	        'question_tag',
        	        'Apps\Common\Models\Question.question_state as question_state',
        	        'Apps\Common\Models\Question.is_expert_reply as is_expert_reply'
        			])
        			->leftJoin('Apps\Common\Models\UserBase',
        					'Apps\Common\Models\Question.user_id=u.user_id','u')
        					->where("$where and Apps\Common\Models\Question.question_state > 0 ")
        					->orderBy($orderBy)
        					->limit($count,$offset)
        					->execute()->toArray();
        	$QuestionFollow = new QuestionFollow();
        	foreach ($list as $k=>$v){
        	    // 是否收藏过
        	    if ($userid) {
        	        $list[$k]['is_collection'] = $QuestionFollow->is_follow($v['question_id'], $userid);
        	    } else {
        	        $list[$k]['is_collection'] = '0';
        	    }
        		$list[$k]['question_pics']=json_decode($list[$k]['question_pics'],true);
        		if(unserialize(base64_decode($list[$k]['question_content']))){
        		    $list[$k]['question_content'] = unserialize(base64_decode($list[$k]['question_content']));
        		}
        		
        		$list[$k]['question_tag'] = $v['question_tag'] ? json_decode($v['question_tag'], true) : null;
        		
        		if(count($list[$k]['question_pics']) > 2){
        			$list[$k]['question_pics'] =  array_slice($list[$k]['question_pics'], 0, 2);
        		}
        		$list[$k]['user_cover']="http://img.meelier.com/".$list[$k]['user_cover'];
        		foreach ($list[$k]['question_pics'] as $key=>$val){
        			$list[$k]['question_pics'][$key]="http://img.meelier.com/".$list[$k]['question_pics'][$key];
        		}
        	}
        	if(count($list)==0){
        		unset($list);
        	}
        	$this->setResult($list);
        	
        }
    }
    /**
     * mysql 查询json数据 中文转Unicode编码 
     * @date: 2016年2月23日 
     * @author: 545
     */
    private function mysql_unicode_encode($name)
    {
        $name = iconv('UTF-8', 'UCS-2', $name);
        $len = strlen($name);
        $str = '';
        for ($i = 0; $i < $len - 1; $i = $i + 2)
        {
            $c = $name[$i];
            $c2 = $name[$i + 1];
            if (ord($c) > 0)
            {    // 两个字节的文字
                $str .= '\\\\\\\\u'.base_convert(ord($c), 10, 16).base_convert(ord($c2), 10, 16);
            }
            else
            {
                $str .= '\\\\\\'.$c2;
            }
        }
        return $str;
    }
}